package 链表;

class MyLinkedList {
    private ListNode first;
    private int size;
    /** Initialize your data structure here. */
    public MyLinkedList() {
        
    }
    
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        return node(index).val;
    }
    
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    public void addAtHead(int val) {
        addAtIndex(0, val);
    }
    
    /** Append a node of value val to the last element of the linked list. */
    public void addAtTail(int val) {
        addAtIndex(size, val);
    }
    
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    public void addAtIndex(int index, int val) {
        if (index < 0) index = 0;
        rangeCheckForAdd(index);
        if (index == 0) {
            ListNode newNode = new ListNode(val);
            newNode.next = first;
            first = newNode;
        } else {
            ListNode prev = node(index-1);
            ListNode newNode = new ListNode(val);
            newNode.next = prev.next;
            prev.next = newNode;
        }
        size++;
    }
    
    /** Delete the index-th node in the linked list, if the index is valid. */
    public void deleteAtIndex(int index) {
        rangeCheck(index);
        if (index == 0) {
            first = first.next;
        } else {
            ListNode prev = node(index - 1);
            prev.next = prev.next.next;
        }
        size--;
    }

    private  ListNode node(int index) {
        rangeCheck(index);
        ListNode node = first;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    private void outOfBounds(int index) {
        // throw new IndexOutOfBoundsException("Index:" + index + ", sieze:" + size);
        return;
    }

    private void rangeCheck(int index) {
        if (index < 0 || index >= size) {
            outOfBounds(index);
        }
    }
    
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size) {
            outOfBounds(index);
        }
    }

    @Override
    public String toString() {

        StringBuilder string = new StringBuilder();
        string.append("size :").append(size).append("[");
        ListNode node = first;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(node.val);
            node = node.next;
        }
        string.append("]");

        return string.toString();
    }
}